package org.liaohailong.helloworld.study;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * Author: liaohailong
 * Time: 2021/5/10 16:41
 * Describe:
 */
public class DFS {

    public int findTargetSumWays(int[] nums, int target) {
        int depth = 0;
        int maxDepth = nums.length - 1;
        int[] res = new int[]{0};

        traversal(nums, 0, target, true, depth, maxDepth, res);
        traversal(nums, 0, target, false, depth, maxDepth, res);
        return res[0];
    }

    private void traversal(int[] nums,
                           int total,
                           int target,
                           boolean left,
                           int depth,
                           int maxDepth,
                           int[] res) {
        int num = nums[depth];
        num = left ? -num : num;
        total += num;

        if (depth == maxDepth) {
            if (total == target) res[0] = res[0] + 1;
            return;
        }

        depth++;
        traversal(nums, total, target, left, depth, maxDepth, res);
        traversal(nums, total, target, !left, depth, maxDepth, res);
    }


    // LC 前序遍历 - 栈结构
    public List<Integer> inorderTraversal(TreeNode root) {
        LinkedList<Integer> result = new LinkedList<>();

        Stack<TreeNode> stack = new Stack<>();

        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            TreeNode top = stack.pop();
            result.add(top.val);
            root = top.right;
        }

        return result;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
